package com.sixfoot;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class Server {
	public static ArrayList<Socket> socketList = new ArrayList<>();
	
	public void start(int port) throws IOException {
		ServerSocket ss = new ServerSocket(port);
		while (true) {
			Socket s = ss.accept();
			socketList.add(s);
			new Thread(new ServerThread(s)).start();
//			PrintStream  ps = new PrintStream(s.getOutputStream());
//			ps.println("您好，");
//			ps.close();
//			s.close();
		}
	}
}

class ServerThread implements Runnable {
	Socket s = null;
	BufferedReader br = null;
	
	public ServerThread(Socket s) throws IOException {
		this.s = s;
		br = new BufferedReader(new InputStreamReader(s.getInputStream()));
	}
	
	@Override
	public void run() {
//		try {
			String content = null;
			while ((content = readFromClient()) != null) {
				System.out.println(content);
//				for (Socket s : Server.socketList) {
//					PrintStream ps = new PrintStream(s.getOutputStream());
//					ps.println(content);
//				}
			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
	}

	private String readFromClient() {
		try {
			return br.readLine();
		} catch (IOException e) {
			Server.socketList.remove(s);
		}
		return null;
	}
	
}